<template>
  <div style="width: 100%">
    <TEditor v-model="content" />
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="typeOpen" :title="typeTitle" width="300">
      <el-form label-width="80" ref="componentTypeRef">
        <el-row>
          <el-col :span="24">
            <el-form-item label="控件类型：" prop="selectCompoentType">
              <el-select v-model="selectCompoentType" placeholder="请选择控件类型" filterable clearable>
                <el-option v-for="dict in sys_field_type" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="saveUpdateComponentType">保 存</el-button>
          <el-button type="danger" @click="typeOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="childTdOpen" :title="childTdTitle" width="300">
      <el-form label-width="80">
        <el-row>
          <el-col :span="24">
            <el-form-item label="结尾列：" prop="endTdNumber">
              <el-input-number v-model="childTdForm.endTdNumber" :min="1" :max="100" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="结尾行：" prop="endTrNumber">
              <el-input-number v-model="childTdForm.endTrNumber" :min="1" :max="100" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="saveChildTdForm">保 存</el-button>
          <el-button type="danger" @click="childTdOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="jcxmOpen" title="更改检测项目" width="400" @close="jcxmClose">
      <el-form-item label="检测项目：" label-width="80">
        <el-select v-model="jcxmId" clearable filterable remote reserve-keyword remote-show-suffix
          :remote-method="remoteMethod" :loading="loading" style="width: 100%" multiple :multiple-limit="20">
          <el-option v-for="item in jcxmList" :key="item.jcxmId" :value="item.jcxmId" :label="item.jcxmName">
            <span v-html="getSupAndSub(item.jcxmName)"></span>
          </el-option>
        </el-select>
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="saveJcxmId">保 存</el-button>
          <el-button type="danger" @click="jcxmOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable :close-on-click-modal="false"
      v-model="pointCountOpen" title="设置小数点位数" width="300">
      <el-form-item label="小数点位数：">
        <el-input-number v-model="pointCount" :min="1" :max="10" :precision="0" />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="savePointCount">保 存</el-button>
          <el-button type="danger" @click="pointCountOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getTable, saveTable, getJcxmList } from "@/api/templateEditor/table.js";
import TEditor from "@/components/TEditor";
import $ from "jquery";
import bus from "@/utils/eventBus";
import useRouteView from "@/store/modules/routeView";
import { nextTick } from "vue";

const routeViewStore = useRouteView();
const route = useRoute();
const { proxy } = getCurrentInstance();
const router = useRouter();
const tableId = ref();
const content = ref("");
const editor = ref();
const componentList = ref([]);
const typeOpen = ref(false);
const childTdOpen = ref(false);
const typeTitle = ref("更改控件类型");
const childTdTitle = ref("子表列信息");
const { sys_field_type } = proxy.useShareDict("sys_field_type");
const selectCompoentType = ref();
const selectedTd = ref();
const tableData = ref();
const childTdForm = ref({
  endTdNumber: 1,
  endTrNumber: 1,
});
const jcxmId = ref("");
const loading = ref(false);
const jcxmOpen = ref(false);
const jcxmList = ref([]);
const pointCount = ref();
const pointCountOpen = ref(false);
bus.off("handleField");
bus.on("handleField", (data) => {
  nextTick(() => {
    let ed = editor.value;
    let tdObject = ed.dom.getParent(ed.selection.getStart(), "td");
    if (tdObject == null) {
      tdObject = getSelectedTarget();
      if (tdObject == null) {
        proxy.$modal.msgError("插入控件失败，未定位到要插入的位置！");
        return false;
      }
    }
    let $td = $(tdObject);
    $td.css("padding", "0 5.4pt");
    //sourceType：3自定义控件，场景应用：删除自定义后再在此区域再次插入控件(sourceType必须相同)可以保持componentId不变。
    if (
      $td.hasClass("component") &&
      $td.attr("sourceType") &&
      $td.attr("sourceType") == 3 &&
      data.sourceType == 3 &&
      $td.attr("name")
    ) {
      data.componentId = $td.attr("name");
    }
    ed.dom.setAttrib(tdObject, "contenteditable", "false");
    ed.dom.setAttrib(tdObject, "name", data.componentId);
    tdObject.innerHTML = "[" + data.componentName + "]";
    if ($(tdObject).hasClass("childTd")) {
      tdObject.className = "component mceNonEditable childTd";
    } else {
      tdObject.className = "component mceNonEditable";
    }
    ed.dom.setAttrib(tdObject, "sourceType", data.sourceType);
    /**
     * type : 1 数据集
     * type : 2 固定字段
     */
    if (data.dId) {
      //数据集控件
      ed.dom.setAttrib(tdObject, "dId", data.dId);
    }
    ed.dom.setAttrib(tdObject, "isWrite", 0);
    data.isWrite = 0;
    if ($(tdObject).parent().hasClass("childTr")) {
      //子表行控件
      data.isMain = 1; //标识当前控件为子表行控件。
    } else if ($(tdObject).hasClass("childTd")) {
      data.isMain = 2; //标识当前控件为子表列控件。
    }
    if (data.componentType && data.componentType == 7) {
      //签字控件（自定义和固定签字控件）
      ed.dom.setAttrib(tdObject, "height", "60");
    }

    setComponentList(data);
    ed.undoManager.add();
    // saveComponent(data);
  });
});

//编辑器初始化完成后获取编辑器对象。
bus.off("initEditorCallBack");
bus.on("initEditorCallBack", (ed) => {
  debugger;
  editor.value = ed;
  setTimeout(() => {
    formatContent();
  }, 1000);
});

function voidShowType(data) {
  let isDay = false;
  let isPoint = false;
  $(editor.value.getBody())
    .find("tr")
    .each(function () {
      // 检查是否包含指定的类名
      if (
        !$(this).hasClass("childTr") &&
        !$(this).hasClass("fixed-head") &&
        !$(this).hasClass("fixed-foot")
      ) {
        // 进行操作，例如修改样式或内容
        $(this)
          .find("td")
          .each(function () {
            if (
              $(this).text().indexOf("采样日期") !== -1 ||
              $(this).text().indexOf("检测日期") !== -1
            ) {
              // 如果是，则返回 true
              isDay = true;
            }
            if (
              $(this).text().indexOf("点位名称") !== -1 ||
              $(this).text().indexOf("采样地点") !== -1 ||
              $(this).text().indexOf("采样点位") !== -1
            ) {
              isPoint = true;
            }
          });
      }
    });
  // 天：2   点位：3   点位+天：4  data.showType
  if (data.showType == 2) {
    if (!isDay && isPoint) {
      return { msg: "整表展示规则为天时未检测到采样日期并且检测到了点位名称" };
    }
    if (!isDay) {
      return { msg: "整表展示规则为天时未检测到采样日期" };
    }
    if (isPoint) {
      return { msg: "整表展示规则为天时检测到点位名称" };
    }
  }
  if (data.showType == 3) {
    if (!isPoint && isDay) {
      return { msg: "整表展示规则为点位时未检测到采样日期并且检测到了采样日期" };
    }
    if (!isPoint) {
      return { msg: "整表展示规则为点位时未检测到点位名称" };
    }
    if (isDay) {
      return { msg: "整表展示规则为点位时检测到采样日期" };
    }
  }
  if (data.showType == 4) {
    if (!isPoint && !isDay) {
      return { msg: "整表展示规则为点位+天时未检测到点位名称和采样日期" };
    }
    if (!isPoint) {
      return { msg: "整表展示规则为点位+天时未检测到点位名称" };
    }
    if (!isDay) {
      return { msg: "整表展示规则为点位+天时未检测到采样日期" };
    }
  }
  if (data.showType == 6) {
    if (!isDay) {
      return { msg: "整表展示规则为天+频次时未检测到采样日期" };
    }
    if (isPoint) {
      return { msg: "整表展示规则为天+频次时不应该出现点位" };
    }
  }
  return {};
}

//保存当前模板
bus.off("transferCenter");
bus.on("transferCenter", (data) => {
  let rs = {};
  if (data.tableMain == 0 && data.modelType == 1) {
    rs = voidShowType(data);
  }
  if (rs.msg) {
    proxy.$modal.confirm(rs.msg).then(() => {
      if (!violidDate()) {
        proxy.$modal.confirm("检测到没有采样日期控件").then(() => {
          SaveTemplate(data);
        });
      } else {
        SaveTemplate(data);
      }
    });
    return;
  }
  if (!violidDate()) {
    proxy.$modal.confirm("检测到没有采样日期控件").then(() => {
      SaveTemplate(data);
    });
    return;
  }
  SaveTemplate(data);
});

function violidJcxm() {
  let jcxms = $(editor.value.getBody()).find("[data-jcxm_id]");
  if (jcxms.length > 0) {
    let isNext = true;
    jcxms.each(function () {
      if (!$(this).hasClass("resultValue")) {
        return (isNext = false);
      }
    });
    return isNext;
  }
  return true;
}

function violidDate() {
  const $body = $(editor.value.getBody());
  let isNext = true;
  $body.find("td").each(function () {
    const $td = $(this);
    if ($td.text().indexOf("采样日期") != -1 && $td.text().indexOf("[") == -1) {
      if ($body.find("td[name='1666351138036711426']").length == 0) {
        return (isNext = false);
      }
    }
  });
  return isNext;
}

function formatContent() {
  const $editor = $(editor.value.getBody());
  $editor.find("table").each(function(){
    $(this).css("height", "auto");
  });
  $editor.find('*').removeAttr('nowrap');
}

function tableValidateTdConnt() {
  const $editor = $(editor.value.getBody());
  let flag = true;
  debugger;
  $editor.find("table").each(function () {
    let tdCount = 0;
    $(this).find("tr").each(function () {
      const $tds = $(this).find("td");
      if ($tds.length == 1 || tdCount >= $tds.length) {
        return true;
      }
      let tempTdCount = 0;
      $tds.each(function () {
        if($(this).attr("rowspan") && $(this).attr("rowspan") > 1){
          return false;
        }
        tempTdCount += $(this).attr("colspan") ? parseInt($(this).attr("colspan")) : 1;
      });
      if (tdCount < tempTdCount) {
        tdCount = tempTdCount;
      }
    })
    if (tdCount > 0) {
      $(this).find("tr").each(function () {
        if ($(this).children("td").length == 1 && $(this).find("td").attr("colspan") != tdCount) {
          const $parentTr = $(this).parent();
          if($parentTr.length == 0){
            return true;
          }
          let isRowsSpan = false;
          $parentTr.find("td").each(function(){
            if($(this).attr("rowspan") && $(this).attr("rowspan") > 1){
              isRowsSpan = true;
              return false;
            }
          });
          if(isRowsSpan){
            return true;
          }
          $(this).find("td").attr("colspan", tdCount);
          if(flag){
            flag = false;
          }
          debugger;
        }
      })
    }
  })
  return flag;
}

function tableValidateWidth() {
  const $editor = $(editor.value.getBody());
  let flag = true;
  $editor.find("table").each(function () {
    const width = $(this).width();
    console.log(width);
    var tableWidthPt = Math.round(width / 96 * 72); 
    if(tableWidthPt > 800){
        flag = false;
        return flag;
    }
  });
  return flag;
}

function SaveTemplate(data) {
  if(!tableValidateTdConnt()){
    proxy.$modal.msgError("检测到当前表格中的单元格不统一，已自动修复，请再次点击保存！");
    return;
  }
  if(!tableValidateWidth()){
    proxy.$modal.alertError("当前表格设置的宽度超出了打印的最大宽度，请给表格设置800pt以下的宽度值！");
    return false;
  }
  let tableData;
  if (data) {
    //来源于其它页面的保存。
    tableData = data;
  } else {
    //来源于当前编辑器的保存
    tableData = { tableId: tableId.value };
  }
  let ed = editor.value;
  if (!violidJcxm()) {
    proxy.$modal.msgError("请给指定的检测项目添加结果控件");
    return;
  }
  //获取编辑器内容。
  tableData.tableContent = ed.getContent();
  let newComponentList = [];
  let parentIds = [];
  let parentIdIsMain = {};
  //校验控件列表与模板内容中的控件是否一致，如果不一致则生成一份新的控件列表。
  for (let i = 0; i < componentList.value.length; i++) {
    let component = componentList.value[i];
    if (validateComponet(component)) {
      newComponentList.push(component);
    } else {
      continue;
    }
    if (!component.isMain) component.isMain = 0;
    if (!treeData.value) continue;

    if (componentList.value[i].sourceType == 2 && componentList.value[i].dataType != 1) {
      treeData.value.forEach((item) => {
        if (item.dataType == 1) {
          if (item.componentId == componentList.value[i].componentId) {
            componentList.value[i].dataType = 1;
          }
        }
      });
    }
    let treeItem = treeData.value.find((item1) => {
      return item1.componentId == component.componentId;
    });
    if (!treeItem) continue;
    if (component.isUnique == 1 || component.isHide == 1) continue;
    let parentId = treeItem.parentId;
    if (parentIds.indexOf(parentId) == -1 && component.isUnique == 0) {
      parentIds.push(parentId);
      parentIdIsMain[parentId] = component.isMain;
    }
  }
  if (parentIds.length > 0) {
    newComponentList = newComponentList.filter((item) => {
      return item.isUnique == 0 && item.isHide == 0;
    });
  }
  for (let parentId of parentIds) {
    let treeItems = treeData.value.filter((item1) => {
      return item1.parentId == parentId && (item1.isUnique == 1 || item1.isHide == 1);
    });
    if (treeItems.length > 0) {
      for (let treeItem of treeItems) {
        treeItem.isMain = parentIdIsMain[parentId];
        treeItem.isHide = !treeItem.isHide ? 0 : 1;
        treeItem.isUnique = !treeItem.isUnique ? 0 : 1;
        treeItem.dataType = !treeItem.dataType ? 0 : 1;
      }
      newComponentList = newComponentList.concat(treeItems);
    }
  }
  //判断子表控件中是否只包含隐藏或唯一控件，如果包含则删除。
  const childComponentList = newComponentList.filter((item) => {
    return item.isMain == 1;
  });
  if (childComponentList.length > 0) {
    const hideOrUniqueComList = childComponentList.filter((item) => {
      return item.isUnique == 1 || item.isHide == 1;
    });
    if (hideOrUniqueComList.length == childComponentList.length) {
      newComponentList = newComponentList.filter((item) => {
        return item.isMain != 1;
      });
    }
  }
  formatContent();
  tableData.componentList = newComponentList;
  bus.emit("getconditionList", tableData);
  saveTable(tableData).then((res) => {
    proxy.$modal.msgSuccess("保存成功！");
    showTable();
  });
}

const treeData = ref([]);
bus.off("oldTree");
bus.on("oldTree", (val) => {
  treeData.value = val;
});

bus.off("deleteComponent");
bus.on("deleteComponent", () => {
  let $targetComponent = $(editor.value.getBody()).find("td.selected");
  if ($targetComponent.length == 0 || !validateComponetDom($targetComponent[0]))
    return false;
  let componentId = $targetComponent.attr("name");
  $targetComponent.removeAttr("contenteditable name sourcetype did");
  $targetComponent.removeClass("component mceNonEditable resultValue hlValue");
  $targetComponent.html("&nbsp;");
  componentList.value = componentList.value.filter((item) => {
    return item.componentId != componentId;
  });

  let temp = componentList.value.filter((item) => {
    return item.isHide == 0;
  });
  if (temp.length !== 0) {
    temp[0].del = 1;
  }
  bus.emit("tempComponent", temp);
});

// 点击公式回显选中单元格
bus.off("selectFormula");
bus.on("selectFormula", (componentId) => {
  let $td = $(editor.value.getBody()).find("td[name='" + componentId + "']");
  if ($td.length == 0) return false; //移除未选中单元格的背景色。
  $td.parents("body").find("td.selected").removeClass("selected");
  $td.addClass("selected");
});

//编辑器内容的单行事件，用于给选中的单元格添加选中背景色。
bus.off("editorClick");
bus.on("editorClick", (e) => {
  let $td = $(e.target);
  //单击后控件选择左侧单行颜色更改
  bus.emit("selectedColor", $td.attr("name"));
  //移除未选中单元格的背景色。
  $td.parents("body").find("td.selected").removeClass("selected");
  if ($td.prop("nodeName").toLowerCase() == "td") {
    $td.addClass("selected");
  } else {
    let $selectedTd = $td.parents("td:first");
    if ($selectedTd.length > 0) {
      $selectedTd.addClass("selected");
    }
  }
  let flag = false;
  if ($td.hasClass("component") && $td.attr("sourceType") == 3) {
    let tdContent = $td.text();
    let name = $td.attr("name");
    if (!name) return;
    for (let i = 0; i < componentList.value.length; i++) {
      let component = componentList.value[i];
      if (component.componentId == name) {
        if (tdContent.startsWith("[") && tdContent.endsWith("]")) {
          //在自定义控件表单中回显自定义组件
          bus.emit("setPropertiesForm", JSON.parse(JSON.stringify(component)));
        } else {
          //说明当前控件在编辑器中删除了，但可以回显，componentId仍然可以使用，但因为删除了，其它信息不需要回显，防止误删除了，重新创建componentId导致数据库表重新创建字段。
          bus.emit("setPropertiesForm", { componentId: name });
        }
        flag = true;
        break;
      }
    }
  }
  if (!flag) {
    bus.emit("setPropertiesForm", {});
  }
});

//编辑器选中双击事件
bus.off("editorDbClick");
bus.on("editorDbClick", (e) => { });

//选中子表行的回显事件。
bus.off("childTrCallBack");
bus.on("childTrCallBack", (trObject) => {
  let $tr = $(trObject);
  let childTrCount = $(editor.value.getBody()).find("tr.childTr").length;
  if (childTrCount > 0 && !$tr.prev().hasClass("childTr")) {
    proxy.$modal.msgError("当前模板中只能有一个子表行！");
    return false;
  }
  let domComponents = $tr.find(".component");
  if (domComponents.length == 0 && !$tr.prev().hasClass("childTr")) {
    proxy.$modal.msgError("当前行没有控件，不能设置为子表行！");
    return false;
  }
  if (!$tr.prev().hasClass("childTr")) {
    let flag = false;
    domComponents.each(function () {
      if (validateComponetDom(this)) {
        for (let i = 0; i < componentList.value.length; i++) {
          let component = componentList.value[i];
          if (component.componentId == $(this).attr("name")) {
            component.isMain = 1; //当前控件属性子表行,标注当前控件为子表控件。
            flag = true;
            break;
          }
        }
      }
    });
    if (!flag) {
      //当前行只有一个控件就可以将当前行设置为子表行。
      proxy.$modal.msgError("当前行没有控件，不能设置为子表行！");
      return false;
    }
  }
  $tr.addClass("childTr");
  editor.value.undoManager.add();
});

//移除子表行
bus.off("remvoeChildTrCallBack");
bus.on("remvoeChildTrCallBack", (trObject) => {
  let $tr = $(trObject);
  $tr.removeClass("childTr child-write");
  let domComponents = $tr.find(".component");
  if (domComponents.length == 0) return;
  //将子表行的控件去掉子表行的标识。
  domComponents.each(function () {
    if (validateComponetDom(this)) {
      for (let i = 0; i < componentList.value.length; i++) {
        let component = componentList.value[i];
        if (component.componentId == $(this).attr("name")) {
          delete component.isMain; //删除子表行标识。
          break;
        }
      }
    }
  });
  editor.value.undoManager.add();
});

//更改控件类型（只针对更改数据集类型）
bus.off("childTdCallBack");
bus.on("childTdCallBack", (tdObject) => {
  if (!validateComponetDom(tdObject)) {
    proxy.$modal.msgError("请添加控件！");
    return false;
  }
  selectedTd.value = tdObject;
  childTdOpen.value = true;
});

bus.off("makeEditableCallBack");
bus.on("makeEditableCallBack", (tdObject) => {
  tdObject.setAttribute("isWrite", 1);
  let component = getComponentById(tdObject.getAttribute("name"));
  if (!component) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  component.isWrite = 1;
});

bus.off("removeMakeEditableCallBack");
bus.on("removeMakeEditableCallBack", (tdObject) => {
  tdObject.setAttribute("isWrite", 0);
  let component = getComponentById(tdObject.getAttribute("name"));
  if (!component) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  component.isWrite = 0;
});

//更改控件类型（只针对更改数据集类型）
bus.off("updateComponentType");
bus.on("updateComponentType", (tdObject) => {
  if (!validateComponetDom(tdObject)) {
    proxy.$modal.msgError("不是有效的数据集控件！");
    return false;
  }
  selectedTd.value = tdObject;
  typeOpen.value = true;
  editor.value.undoManager.add();
});

//添加或移除表头
bus.off("updateFixedHead");
bus.on("updateFixedHead", (trObject) => {
  let $tr = $(trObject);
  if ($tr.length == 0) {
    proxy.$modal.msgError("只能为表格行设置表头！");
    return false;
  }
  if ($tr.hasClass("fixed-head")) {
    $tr.removeClass("fixed-head");
  } else {
    $tr.addClass("fixed-head");
  }
  editor.value.undoManager.add();
});

//添加或移除表头
bus.off("updateFixedFoot");
bus.on("updateFixedFoot", (trObject) => {
  let $tr = $(trObject);
  if ($tr.length == 0) {
    proxy.$modal.msgError("只能为表格行设置表尾！");
    return false;
  }
  if ($tr.hasClass("fixed-foot")) {
    $tr.removeClass("fixed-foot");
  } else {
    $tr.addClass("fixed-foot");
  }
  editor.value.undoManager.add();
});

//自由填写添加或移除表头
bus.off("updateChildWrite");
bus.on("updateChildWrite", (trObject) => {
  let $tr = $(trObject);
  if ($tr.length == 0) {
    proxy.$modal.msgError("只能为表格行设置自由填写功能！");
    return false;
  }
  if ($tr.hasClass("child-write")) {
    $tr.removeClass("child-write");
  } else {
    $tr.addClass("child-write");
  }
  editor.value.undoManager.add();
});

//给指定的控件添加结果标识
bus.off("updateResultValue");
bus.on("updateResultValue", (tdObject) => {
  let $td = $(tdObject);
  if ($td.length == 0) {
    proxy.$modal.msgError("只能为单元格添加结果值！");
    return false;
  }
  if (!validateComponetDom(tdObject)) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  let component = getComponentById($td.attr("name"));
  if (!component) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  if ($td.hasClass("resultValue")) {
    $td.removeClass("resultValue");
    component.isResult = 0;
    proxy.$modal.msgSuccess("移除成功！");
  } else {
    $td.addClass("resultValue");
    component.isResult = 1;
    proxy.$modal.msgSuccess("设置成功！");
  }
  editor.value.undoManager.add();
});

//给指定的控件添加结果标识
bus.off("updateIsRowavg");
bus.on("updateIsRowavg", (tdObject) => {
  let $td = $(tdObject);
  if ($td.length == 0) {
    proxy.$modal.msgError("只能为单元格添加结果均值！");
    return false;
  }
  if (!validateComponetDom(tdObject)) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  let component = getComponentById($td.attr("name"));
  if (!component) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  if ($td.hasClass("isRowavg")) {
    $td.removeClass("isRowavg");
    component.isRowavg = 0;
    proxy.$modal.msgSuccess("移除成功！");
  } else {
    $td.addClass("isRowavg");
    component.isRowavg = 1;
    proxy.$modal.msgSuccess("设置成功！");
  }
  editor.value.undoManager.add();
});

//给指定的控件添加求和标识
bus.off("updateIsRowsum");
bus.on("updateIsRowsum", (tdObject) => {
  let $td = $(tdObject);
  if ($td.length == 0) {
    proxy.$modal.msgError("只能为单元格添加求和控件！");
    return false;
  }
  if (!validateComponetDom(tdObject)) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  let component = getComponentById($td.attr("name"));
  if (!component) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  if ($td.hasClass("isRowsum")) {
    $td.removeClass("isRowsum");
    component.isRowsum = 0;
    proxy.$modal.msgSuccess("移除成功！");
  } else {
    $td.addClass("isRowsum");
    component.isRowsum = 1;
    proxy.$modal.msgSuccess("设置成功！");
  }
  editor.value.undoManager.add();
});

//给指定的控件添加求和标识
bus.off("updateRequired");
bus.on("updateRequired", (tdObject) => {
  let $td = $(tdObject);
  if ($td.length == 0) {
    proxy.$modal.msgError("只能为单元格添加求和控件！");
    return false;
  }
  if (!validateComponetDom(tdObject)) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  let component = getComponentById($td.attr("name"));
  if (!component) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  if ($td.hasClass("required")) {
    $td.removeClass("required");
    component.required = 0;
    proxy.$modal.msgSuccess("移除成功！");
  } else {
    $td.addClass("required");
    component.required = 1;
    proxy.$modal.msgSuccess("设置成功！");
  }
  editor.value.undoManager.add();
});

const pointCountTd = ref();
//给指定的控件添加求和标识
bus.off("updateLimitPointCount");
bus.on("updateLimitPointCount", (tdObject) => {
  if (!validateComponetDom(tdObject)) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  let component = getComponentById($(tdObject).attr("name"));
  if (typeof component.pointCount == "number") {
    pointCount.value = component.pointCount;
  } else {
    pointCount.value = null;
  }
  pointCountTd.value = tdObject;
  pointCountOpen.value = true;
});

function savePointCount() {
  debugger;
  if (!validateComponetDom(pointCountTd.value)) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  pointCountOpen.value = false;
  let component = getComponentById($(pointCountTd.value).attr("name"));
  if (!pointCount.value) {
    delete component.pointCount;
    return;
  }
  component.pointCount = pointCount.value;
}
//给指定的控件添加结果标识
bus.off("updateHlValue");
bus.on("updateHlValue", (tdObject) => {
  let $td = $(tdObject);
  if ($td.length == 0) {
    proxy.$modal.msgError("只能为单元格添加含量值！");
    return false;
  }
  if (!validateComponetDom(tdObject)) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  let component = getComponentById($td.attr("name"));
  if (!component) {
    proxy.$modal.msgError("当前选择不是有效控件！");
    return false;
  }
  if ($td.hasClass("hlValue")) {
    $td.removeClass("hlValue");
    component.isHl = 0;
    proxy.$modal.msgSuccess("移除成功！");
  } else {
    $td.addClass("hlValue");
    component.isHl = 1;
    proxy.$modal.msgSuccess("设置成功！");
  }
  editor.value.undoManager.add();
});

//自由填写添加或移除表头
bus.off("getTableData");
bus.on("getTableData", (callback) => {
  callback.modelType = tableData.value.modelType;
});
//返回到列表页
bus.off("returnListPage");
bus.on("returnListPage", () => {
  proxy.$tab.closePage().then(() => {
    router.push({
      path: "/templateEditor/table",
    });
  });
});

const jcxmTd = ref();
// 更改检测项目
bus.off("addJcxmCallBack");
bus.on("addJcxmCallBack", (tdObject) => {
  if (tdObject.hasAttribute("data-jcxm_id") && tdObject.hasAttribute("data-jcxm_name")) {
    const jcxmNames = tdObject.getAttribute("data-jcxm_name").split("、");
    const jcxmIds = tdObject.getAttribute("data-jcxm_id").split(",");
    jcxmList.value = [];
    for (let i = 0; i < jcxmIds.length; i++) {
      jcxmList.value.push({ jcxmName: jcxmNames[i], jcxmId: jcxmIds[i] });
    }
    jcxmId.value = jcxmIds;
  }
  jcxmOpen.value = true;
  jcxmTd.value = tdObject;
});

function getSelectedTarget() {
  let $targetComponent = $(editor.value.getBody()).find("td.selected");
  if ($targetComponent.length == 0) return null;
  return $targetComponent[0];
}
//校验当前控件是否是有效控件。
function validateComponet(component) {
  if (component.isUnique == 1 || component.isHide == 1) return true;
  let $component = $(editor.value.getBody()).find(
    "[name='" + component.componentId + "']"
  );
  if ($component.length > 0) {
    let flag = false;
    $component.each(function () {
      let componentContent = $(this).text();
      if (componentContent.startsWith("[") && componentContent.endsWith("]")) {
        flag = true;
      } else {
        $(this).removeAttr("name");
      }
    });
    return flag;
  }
  return false;
}

//根据编辑器内容的dom节点校验当前控件是否是有效控件
function validateComponetDom(componentDom) {
  let $componentDom = $(componentDom);
  if ($componentDom.hasClass("component") && $componentDom.attr("name")) {
    let componentContent = $componentDom.text();
    if (componentContent.startsWith("[") && componentContent.endsWith("]")) return true;
  }
  return false;
}

/**
 * 判断要插入的控件是否在控件列表中存在，依据componentId判断如果不存在则放到控件列表中。
 * @param {控件对象} component
 */
function setComponentList(component) {
  let flag = false;
  component.isHide = !component.isHide ? 0 : 1;
  component.isUnique = !component.isUnique ? 0 : 1;
  for (let i = 0; i < componentList.value.length; i++) {
    if (componentList.value[i].componentId == component.componentId) {
      componentList.value[i] = component;
      flag = true;
      break;
    }
  }
  if (!flag) {
    componentList.value.push(component);
  }
  bus.emit("tempComponent", componentList.value);
}

function getComponentById(componentId) {
  if (!componentId) return;
  let flag = false;
  for (let i = 0; i < componentList.value.length; i++) {
    if (componentList.value[i].componentId == componentId) {
      return componentList.value[i];
    }
  }
  return;
}

//回显模板信息（模板内容和控件列表）
function showTable() {
  getTable(tableId.value).then((res) => {
    content.value = res.data.tableContent;
    tableData.value = res.data;

    if (res.data.componentList) {
      componentList.value = res.data.componentList;
      bus.emit("tempComponent", componentList.value);
    }
    if (res.data.jsContent) {
      bus.emit("setCodeValue", res.data.jsContent);
    }
    bus.emit("setTableForm", res.data);
  });
}
bus.off("reloadTable");
bus.on("reloadTable", () => {
  showTable();
});
function saveUpdateComponentType() {
  let componentId = $(selectedTd.value).attr("name");
  for (let i = 0; i < componentList.value.length; i++) {
    let component = componentList.value[i];
    if (component.componentId == componentId) {
      component.componentType = selectCompoentType.value;
      typeOpen.value = false;
      break;
    }
  }
}

function saveChildTdForm() {
  let $selectedTd = $(selectedTd.value);
  $selectedTd.addClass("childTd");
  let endTdNumber = childTdForm.value.endTdNumber;
  let endTrNumber = childTdForm.value.endTrNumber;
  $selectedTd.nextAll().each(function (i) {
    if (i + 2 > endTdNumber) {
      endTdNumber = i + 1;
      return true;
    }
    $(this).addClass("childTd");
  });
  let selectedTdIndex = $selectedTd[0].colSpan;
  $selectedTd.prevAll().each(function (i) {
    selectedTdIndex += this.colSpan;
  });
  $selectedTd
    .parent()
    .nextAll()
    .each(function (i) {
      let tdIndex = 0;
      $(this)
        .find("td")
        .each(function (j) {
          tdIndex += this.colSpan;
          if (tdIndex == selectedTdIndex) {
            $(this).addClass("childTd");
            if (validateComponetDom(this)) {
              for (let t = 0; t < componentList.value.length; t++) {
                let component = componentList.value[t];
                if (component.componentId == $(this).attr("name")) {
                  component.isMain = 2; //当前控件属性子表行,标注当前控件为子表控件。
                  break;
                }
              }
            }
            return true;
          }
          if (selectedTdIndex < tdIndex) {
            return true;
          }
        });
      if (i + 2 > endTrNumber) {
        return true;
      }
    });
  $selectedTd.attr("endTdNumber", endTdNumber);
  $selectedTd.attr("endTrNumber", endTrNumber);
  if (validateComponetDom($selectedTd[0])) {
    for (let t = 0; t < componentList.value.length; t++) {
      let component = componentList.value[t];
      if (component.componentId == $selectedTd.attr("name")) {
        component.isMain = 2; //当前控件属性子表行,标注当前控件为子表控件。
        break;
      }
    }
  }
  childTdOpen.value = false;
  proxy.$modal.msgSuccess("添加循环列成功！");
}

// 监听当前模板id的变化（根据模板id打开不同的模板）
// watch(
//   () => route.query.tableId,
//   (newVal, oldVal) => {
//     if (newVal && (!oldVal || newVal != oldVal)) {
//       if (tableId.value !== newVal) {
//
//         tableId.value = route.query.tableId;
//         showTable();
//       }
//     }
//   },
//   { deep: true, immediate: true }
// );
nextTick(() => {
  tableId.value = route.query.tableId;
  showTable();
});

watch(
  () => route,
  (newVal) => {
    if (
      newVal.path == "/templateEditor/template" ||
      newVal.path == "/templateEditor/labTemple" ||
      newVal.path == "/templateEditor/common"
    ) {
      const { path, name, meta } = newVal;
      routeViewStore.setRouteView({ path, name, meta });
    }
  },
  { deep: true, immediate: true }
);

function remoteMethod(val) {
  if (val) {
    loading.value = true;
    setTimeout(() => {
      getJcxmList({ tableId: tableId.value, jcxmName: val }).then((res) => {
        loading.value = false;
        jcxmList.value = res.rows;
      });
    }, 200);
  }
}

function saveJcxmId() {
  let component = getComponentById($(jcxmTd.value).attr("name"));
  if (jcxmTd.value.getAttribute("data-jcxm_id")) {
    if (!jcxmId.value || jcxmId.value.length == 0) {
      proxy.$modal.confirm("确定要移除检测项目吗？").then(() => {
        proxy.$modal.msgSuccess("移除成功");
        jcxmTd.value.removeAttribute("data-jcxm_id");
        jcxmTd.value.removeAttribute("data-jcxm_name");
        jcxmTd.value.classList.remove("addJcxm");
        delete component.jcxmId;
        jcxmOpen.value = false;
      });
      return;
    }
  }
  if (!jcxmId.value) {
    proxy.$modal.msgError("请选择检测项目！");
    return;
  }
  jcxmName.value = proxy.getItemByArrays(
    jcxmList.value,
    "jcxmId",
    jcxmId.value,
    "jcxmName"
  );
  proxy.$modal.msgSuccess("添加成功");
  jcxmTd.value.setAttribute("data-jcxm_id", jcxmId.value);
  jcxmTd.value.setAttribute("data-jcxm_name", jcxmName.value);
  jcxmTd.value.classList.add("addJcxm");
  component.jcxmId = jcxmId.value.join(",");
  jcxmOpen.value = false;
}

function jcxmClose() {
  jcxmList.value = [];
  jcxmId.value = "";
  jcxmName.value = "";
  jcxmTd.value = null;
}

const jcxmName = ref("");
</script>

<style lang="scss" scoped></style>
